var express = require("express");
var router = express.Router();
var path = require("path");
var multer = require("multer");
var fs = require("fs");
const { SuccessModel, ErrorModel } = require("../../model/resModel");

var storage = multer.diskStorage({
  //设置 上传图片服务器位置
  destination: path.resolve(__dirname, "../../public/avatar"),
  //设置 上传文件保存的文件名
  filename: function (req, file, cb) {
    // 获取后缀扩展
    let extName = file.originalname.slice(file.originalname.lastIndexOf(".")); //.jpg
    // 获取名称
    let fileName = Date.now();
    cb(null, fileName + extName);
  },
});
var limits = {
  fieldSize: "50MB", //设置限制（可选）
};
//单张上传
const imageUploader = multer({
  //   fileFilter,
  storage,
  limits,
}).single("file"); //文件上传预定 name 或者 字段

/* GET home page. */
router.post("/", imageUploader, function (req, res, next) {
  console.log(req.file);
  //    fs.unlinkSync('../public/avatar/1592031035405.pdf');
  res.json(new SuccessModel(req.file));
});
router.get("/s", function (req, res, next) {
  fs.unlink(
    path.join(__dirname, "../public/avatar/1592031111652.pdf"),
    (err) => {
      if (err) {
        console.log("error ocurred");
        throw err;
      }
      console.log("successfully d-eleted /tmp/hello");
    }
  );

  res.json("success");
});

module.exports = router;
